using UnityEngine;
using QFramework;

namespace ProjectMyFarmAndShe
{
	public partial class SellItemTemplate : ViewController,IController
	{
		private ShopData mData;
		
		void Start()
		{
			// Code Here
		}

		public void Init(ShopData data)
		{
			mData = data;

			BtnSell.interactable = true;
			
			var toolbarSystem = this.GetSystem<IToolbarSystem>();
			var item = toolbarSystem.ToolbarDatas.Find(data => data.Key == mData.Key);
			if (item != null)
			{
				mData.Count.Value = item.Count.Value;
				CountText.text = mData.Count.Value.ToString();
			}
			else
			{
				CountText.text = 0.ToString();
				mData.Count.Value = 0;
			}

			mData.Count.RegisterWithInitValue(count =>
				{
					if (count > 0)
					{
						BtnSell.interactable = true;
					}
					else
					{
						BtnSell.interactable = false;
					}

					CountText.text = mData.Count.Value.ToString();
				})
				.UnRegisterWhenGameObjectDestroyed(gameObject);
			
			PriceText.text = mData.Price.ToString();
			Icon.sprite = ResController.Default.GetToolIconGetKey(mData.Icon);
			
			BtnSell.onClick.AddListener(() =>
			{
				this.SendCommand(new SubToolbarCountCommand(mData.Key, 1));
				Global.Coin.Value += mData.Price;
				mData.Count.Value--;
				MessagePanel.Default.AddMessage($"出售一个{mData.Name},获得{mData.Price}金币");
				AudioKit.PlaySound("resources://SellItem");
			});
		}

		public IArchitecture GetArchitecture()
		{
			return Global.Interface;
		}
	}
}
